<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>通用模板</title>
</head>
<body>
<script src="../js/vue.js"></script>


<div id="app">
    {{msg}}

    <table border="1">
        <tr>
            <th>id</th>
            <th>名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>小计</th>
        </tr>
        <tr v-for="(item,index) in items" :key="item.id">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td><input type="button" value="-" @click="decrCounts(index)">{{item.count}}<input type="button" value="+"
                                                                                               @click="addCounts(index)">
            </td>
            <td>{{(item.price * item.count).toFixed(2)}}</td>
        </tr>
    </table>
    <h3>总价格:{{getTotalPrice()}}</h3>
</div>

<script>
    var app = new Vue({
        el: "#app",   //element:元素
        data: {        //data:数据 用来vue实例对象绑定一系列数据
            msg: "购物车实现",
            items: [
                {id: 1, name: "iphone12", count: 1, price: 6550},
                {id: 2, name: "iphone11", count: 1, price: 6500}
            ],

        },
        methods: {
            addCounts(index) {
                this.items[index].count++
            },
            decrCounts(index) {
                if (this.items[index].count <= 0) {
                    alert("不能小于0");
                    return
                }
                this.items[index].count--
            },
            getTotalPrice() {
                var totalPrice = 0;
                for (let i = 0; i < this.items.length; i++) {
                    totalPrice += this.items[i].count * this.items[i].price
                }
                return totalPrice;
            }
        }
    });
</script>
</body>
</html>